import java.util.LinkedList;

import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

public class CPUMonitor
{
    public static final int port = 20001;
    public static final int samplelength = 60 * 2;

    private LinkedList<Double> data;
    private double sum;

    private CPUMonitor()
    {
        data = new LinkedList<Double>();
        sum = 0;

        new Thread(new Worker()).start();
    }

    private synchronized void add(double value)
    {
        sum += value;
    }

    private synchronized void sub(double value)
    {
        sum -= value;
    }

    public synchronized double getAvg()
    {
        if (data.size() == 0)
            return 0;
        else
            return sum / data.size();
    }

    private static CPUMonitor ins = new CPUMonitor();

    static public CPUMonitor getInstance()
    {
        return ins;
    }

    class Worker implements Runnable
    {

        @Override
        public void run()
        {
            Sigar sigar = new Sigar();
            while (true)
            {
                try
                {
                    CpuPerc perc = sigar.getCpuPerc();
                    Double value = perc.getCombined();
                    add(value);
                    data.add(value);
                    if (data.size() > samplelength)
                    {
                        sub(data.remove());
                    }

                    Thread.sleep(1000);
                }
                catch (SigarException e)
                {
                    e.printStackTrace();
                }
                catch (InterruptedException e)
                {
                    e.printStackTrace();
                }
            }
        }

    }

    public static void main(String[] args) throws InterruptedException
    {
        while (true)
        {
            System.out.println(getInstance().getAvg());
            Thread.sleep(1000);
        }
    }
}
